import React from 'react';
import {Tree, TreeSelect} from 'antd';
import { OptionType } from '@/types/common';
import {TreeSelectProps} from "antd/lib/tree-select";
import {ChangeEventExtra, DefaultValueType} from "rc-tree-select/lib/interface";

interface CustomTreeSelectProps extends Omit<TreeSelectProps<CustomTreeSelectProps>, "onChange"|"value">{
  list?:OptionType[];
  value? : DefaultValueType
  onChange?:(value:DefaultValueType)=>void
}

interface CustomTreeSelectState{
  value? : DefaultValueType
}

export default class CustomTreeSelect extends React.Component<CustomTreeSelectProps,CustomTreeSelectState> {

  state={
    value:this.props.value
  }

  static getDerivedStateFromProps(nextProps: CustomTreeSelectProps) {
    if ('value' in nextProps) {
      return { value: nextProps.value};
    }
    return null;
  }

  renderTree = (options?:OptionType[]) =>
    options?.map(option => {
      if (option.children) {
        return (
          <Tree.TreeNode
            title={option.name}
            key={option.id}
            // @ts-ignore
            value={option.id}
          >
            {this.renderTree(option.children)}
          </Tree.TreeNode>
        );
      }
      return (
        <TreeSelect.TreeNode
          title={option.name}
          key={option.id}
          // @ts-ignore
          value={option.id}
        />
      );
  });

  onChange=(value: DefaultValueType, labelList: React.ReactNode[], extra: ChangeEventExtra)=>{
    if (!('value' in this.props)) {
      this.setState({ value:value });
    }
    const { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  }

  render() {

    const { list,multiple } = this.props;
    const { value } = this.state;
    return (
      <TreeSelect
        multiple={multiple}
        showSearch={true}
        style={{ width: '100%' }}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="请选择上级功能"
        allowClear
        treeDefaultExpandAll
        value={value}
        onChange={this.onChange}
      >
        {this.renderTree(list)}
      </TreeSelect>
    );
  }
}


